package ru.amse.vlassiev.reader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

public class LogFileReader implements IReader {

	private File myFile;
	private InputStream myIS;
	private int myDelay;
	private IListener myListener;
	
	public LogFileReader(File file, int delay) throws FileNotFoundException {
		myFile = file;
		myIS = new FileInputStream(myFile);
		myDelay = delay;
	}

	public LogFileReader(File file) throws FileNotFoundException {
			this(file, 0);
	}
	

	public Map<String, String> getNextMessage() {
		byte[] byteMessage = new byte[1024];
		try {
			Thread.sleep(myDelay);
			myIS.read(byteMessage);
			return createData(new String(byteMessage));
			
		} catch (IOException e) {
			return null;
		} catch (InterruptedException e) {
			
		}
		return null;
	}
	
	private Map<String, String> createData(String message) {
		Map<String, String> result = new HashMap<String, String>();
		StringTokenizer tokenizer = new StringTokenizer(message, " ", false);
		while (tokenizer.hasMoreTokens()) {
			String token = tokenizer.nextToken();
			if (token.indexOf('=') != -1) {
				String[] keyValue = token.split("=");
				result.put(keyValue[0], keyValue[1]);
			}
		}
		String PRI;
		if (message.indexOf('<') >= 0 && message.indexOf('>') >= 0) {
			PRI = message.substring(message.indexOf('<') + 1, message.indexOf('>'));
		} else {
			PRI = "134";
		}
		result.put("PRI", PRI);
		String timestamp;
		if (message.indexOf('[') >= 0 && message.indexOf(']') >= 0) {
			timestamp = message.substring(message.indexOf('[') + 1, message.indexOf(']'));
		} else {
			timestamp = "0000-00-00 00:00:00";
		}
		result.put("timestamp", timestamp);
		return result;
	}
	
	public void addListener(IListener listener) {
		myListener = listener;
	}
	
	public void start() {
		new Thread(new ReaderAction()).start();
	}
	
	private class ReaderAction implements Runnable {
		public void run() {
			while (true) {
				myListener.newMessage(getNextMessage());
			}
		}
	}
}
